<template>
  <div class="merchant-detail-page" v-loading="loading">
    <div class="container" v-if="merchant">
      <!-- 商家头部信息 -->
      <div class="merchant-header">
        <div class="merchant-banner">
          <el-avatar 
            :src="merchant.avatar" 
            :alt="merchant.name"
            :size="120"
            shape="square"
            fit="cover"
          >
            <el-icon><Shop /></el-icon>
          </el-avatar>
          <div class="merchant-info">
            <h1>{{ merchant.name }}</h1>
            <div class="rating">
              <el-rate v-model="merchant.rating" disabled />
              <span class="rating-text">{{ merchant.rating }} ({{ merchant.reviewCount }}条评价)</span>
            </div>
            <p class="description">{{ merchant.description }}</p>
            <div class="merchant-meta">
              <span class="distance">距离 {{ merchant.distance }}km</span>
              <span class="status" :class="{ online: merchant.isOnline }">
                {{ merchant.isOnline ? '营业中' : '休息中' }}
              </span>
            </div>
          </div>
          <div class="actions">
            <el-button @click="toggleFavorite" :type="isFavorited ? 'warning' : 'default'">
              <el-icon><Star /></el-icon>
              {{ isFavorited ? '已收藏' : '收藏' }}
            </el-button>
            <el-button type="primary" @click="makeAppointment">立即预约</el-button>
          </div>
        </div>
      </div>
      
      <!-- 导航标签 -->
      <div class="nav-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="服务项目" name="services" />
          <el-tab-pane label="商家信息" name="info" />
          <el-tab-pane label="用户评价" name="reviews" />
          <el-tab-pane label="商家相册" name="gallery" />
        </el-tabs>
      </div>
      
      <!-- 内容区域 -->
      <div class="content-area">
        <!-- 服务项目 -->
        <div v-show="activeTab === 'services'" class="services-section">
          <div class="service-categories">
            <div
              v-for="service in services"
              :key="service.id"
              class="category-section"
            >
              <h3 class="category-title">{{ service.name }}</h3>
              <div class="service-grid">
                <div
                  class="service-card"
                >
                  <div class="service-image">
                    <el-avatar :src="service.image" :size="60" shape="square">
                      <el-icon><Box /></el-icon>
                    </el-avatar>
                  </div>
                  <div class="service-info">
                    <h4 class="service-name">{{ service.name }}</h4>
                    <p class="service-description">{{ service.description }}</p>
                    <div class="service-price">
                      <span class="price">¥{{ service.price }}</span>
                      <span class="unit">{{ service.unit }}</span>
                    </div>
                    <el-button type="primary" size="small" @click="selectService(service)">
                      选择
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 商家信息 -->
        <div v-show="activeTab === 'info'" class="info-section">
          <div class="merchant-details">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="营业时间">{{ merchant.businessHours }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ merchant.phone }}</el-descriptions-item>
              <el-descriptions-item label="商家地址">{{ merchant.address }}</el-descriptions-item>
              <el-descriptions-item label="起送价格">¥{{ merchant.minOrder }}</el-descriptions-item>
              <el-descriptions-item label="配送费">¥{{ merchant.deliveryFee }}</el-descriptions-item>
              <el-descriptions-item label="营业状态">
                <el-tag :type="merchant.isOnline ? 'success' : 'danger'">
                  {{ merchant.isOnline ? '营业中' : '休息中' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
        
        <!-- 用户评价 -->
        <div v-show="activeTab === 'reviews'" class="reviews-section">
          <div class="review-summary">
            <div class="rating-overview">
              <div class="big-rating">{{ merchant.rating }}</div>
              <div class="stars">
                <el-rate v-model="merchant.rating" disabled />
                <div class="review-count">{{ merchant.reviewCount }}条评价</div>
              </div>
            </div>
          </div>
          
          <div class="review-list">
            <div
              v-for="review in reviews"
              :key="review.id"
              class="review-item"
            >
              <div class="review-header">
                <el-avatar :src="review.userAvatar" :size="40">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <div class="review-meta">
                  <div class="username">{{ review.username }}</div>
                  <div class="review-time">{{ review.createTime }}</div>
                </div>
                <el-rate v-model="review.rating" disabled size="small" />
              </div>
              <div class="review-content">{{ review.content }}</div>
            </div>
          </div>
          
          <div class="load-more" v-if="hasMoreReviews">
            <el-button @click="loadMoreReviews" :loading="reviewsLoading">
              加载更多评价
            </el-button>
          </div>
        </div>
        
        <!-- 商家相册 -->
        <div v-show="activeTab === 'gallery'" class="gallery-section">
          <div class="gallery-grid">
            <div
              v-for="(image, index) in merchant.gallery"
              :key="index"
              class="gallery-item"
              @click="previewImage(image, merchant.gallery, index)"
            >
              <img :src="image" :alt="`商家图片${index + 1}`" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 联系商家对话框 -->
    <el-dialog v-model="showContactDialog" title="联系商家" width="400px">
      <div class="contact-info">
        <div class="contact-item">
          <el-icon><Phone /></el-icon>
          <span>{{ merchant?.phone }}</span>
          <el-button size="small" @click="callMerchant">拨打电话</el-button>
        </div>
        <div class="contact-item" v-if="merchant?.wechat">
          <el-icon><ChatDotRound /></el-icon>
          <span>{{ merchant.wechat }}</span>
          <el-button size="small" @click="copyWechat">复制微信</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElImageViewer } from 'element-plus'
import { Location, Phone, Clock, Star, ChatDotRound, Shop, Box, User } from '@element-plus/icons-vue'
import { merchantApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const merchant = ref(null)
const services = ref([])
const reviews = ref([])
const activeTab = ref('services')
const reviewsLoading = ref(false)
const hasMoreReviews = ref(true)
const reviewsPage = ref(1)
const showContactDialog = ref(false)
const isFavorited = ref(false)

const fetchMerchantDetail = async () => {
  try {
    loading.value = true
    const response = await merchantApi.getMerchantDetail(route.params.id)
    merchant.value = response.data
  } catch (error) {
    ElMessage.error('获取商家详情失败')
    console.error('获取商家详情失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchReviews = async (page = 1) => {
  try {
    reviewsLoading.value = true
    // 暂时使用模拟数据，等待后端API实现
    const mockReviews = [
      {
        id: 1,
        username: '用户1',
        userAvatar: '',
        rating: 5,
        content: '服务很好，很满意！',
        createTime: '2024-01-01'
      }
    ]

    if (page === 1) {
      reviews.value = mockReviews
    } else {
      reviews.value.push(...mockReviews)
    }

    hasMoreReviews.value = false
  } catch (error) {
    ElMessage.error('获取评价失败')
  } finally {
    reviewsLoading.value = false
  }
}

const handleTabChange = (tabName) => {
  if (tabName === 'reviews' && reviews.value.length === 0) {
    fetchReviews()
  }
}

const toggleFavorite = async () => {
  try {
    // 暂时使用本地状态，等待后端API实现
    if (isFavorited.value) {
      isFavorited.value = false
      ElMessage.success('已取消收藏')
    } else {
      isFavorited.value = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const makeAppointment = () => {
  router.push(`/services?merchantId=${merchant.value.id}`)
}

const selectService = (service) => {
  router.push(`/services/${service.id}?merchantId=${merchant.value.id}`)
}

const loadMoreReviews = () => {
  reviewsPage.value++
  fetchReviews(reviewsPage.value)
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

const previewImage = (image, images = [image], index = 0) => {
  ElImageViewer({
    urlList: images,
    initialIndex: index
  })
}

const callMerchant = () => {
  window.location.href = `tel:${merchant.value.phone}`
}

const copyWechat = async () => {
  try {
    await navigator.clipboard.writeText(merchant.value.wechat)
    ElMessage.success('微信号已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

onMounted(() => {
  fetchMerchantDetail()
})
</script>

<style scoped>
.merchant-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.merchant-header {
  background: white;
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.merchant-banner {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.merchant-info {
  flex: 1;
}

.merchant-info h1 {
  font-size: 28px;
  margin: 0 0 10px 0;
  color: #333;
}

.rating {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.rating-text {
  color: #666;
  font-size: 14px;
}

.description {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.6;
}

.merchant-meta {
  display: flex;
  gap: 20px;
  color: #999;
  font-size: 14px;
}

.status.online {
  color: #67c23a;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.nav-tabs {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-area {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-section {
  margin-bottom: 40px;
}

.category-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.service-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.service-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.service-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.service-image {
  height: 160px;
  overflow: hidden;
}

.service-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.service-info {
  padding: 16px;
}

.service-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.service-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
  line-height: 1.5;
}

.service-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
  margin-bottom: 12px;
}

.price {
  font-size: 20px;
  font-weight: 600;
  color: #e6a23c;
}

.unit {
  font-size: 14px;
  color: #666;
}

.info-section {
  padding: 20px 0;
}

.merchant-details {
  padding: 20px 0;
}

.reviews-section {
  padding: 20px 0;
}

.review-summary {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 20px;
}

.big-rating {
  font-size: 48px;
  font-weight: 600;
  color: #409eff;
}

.review-count {
  color: #666;
  font-size: 14px;
  margin-top: 5px;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
}

.review-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.review-meta {
  flex: 1;
}

.username {
  font-weight: 500;
  color: #333;
}

.review-time {
  color: #999;
  font-size: 12px;
}

.review-content {
  color: #666;
  line-height: 1.6;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.gallery-item {
  aspect-ratio: 1;
  overflow: hidden;
  border-radius: 8px;
  cursor: pointer;
}

.gallery-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.gallery-item:hover img {
  transform: scale(1.05);
}

.load-more {
  text-align: center;
  margin-top: 30px;
}

.contact-info {
  padding: 20px 0;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.contact-item span {
  flex: 1;
  font-weight: 500;
}

@media (max-width: 768px) {
  .merchant-banner {
    flex-direction: column;
    text-align: center;
  }
  
  .service-grid {
    grid-template-columns: 1fr;
  }
  
  .service-card {
    flex-direction: column;
    text-align: center;
  }
  
  .rating-overview {
    flex-direction: column;
    text-align: center;
  }
  
  .gallery-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style> 